//
//  LXMineViewController.m
//  LvXi_newVersion
//
//  Created by 诸葛孔明 on 16/8/10.
//  Copyright © 2016年 SJT. All rights reserved.
//............................................................................................//
//...........................................个人中心...........................................//
//............................................................................................//

#import "LXMineViewController.h"
#import "LXMineHeaderView.h"
#import "UIImage+LxImage.h"
#import "LXPreparePayViewCell.h"
#import "LXMineCenterButton.h"
#import "LXNoHighLightViewCell.h"
#import "LXMineCommissionViewCell.h"
#import "LXLoginViewController.h"
#import "SettingTableViewController.h"
#import "LXAccountSettingViewController.h"
#import "LXMySaleViewController.h"
#import "LXLoginStyleViewController.h"
#import "LXFeedbackViewController.h"
#import "LXLoginViewController.h"

static NSString *const LXPreparePayViewCellID = @"LXPreparePayViewCell";
static NSString *const LXNoHighLightViewCellID = @"LXNoHighLightViewCell";
static NSString *const LXMineCommissionViewCellID = @"LXMineCommissionViewCell";
static NSString *const LXCommonCellID = @"LXCommonCell";

@interface LXMineViewController ()<UITableViewDelegate,UITableViewDataSource>{
    LXLoginViewController * _loginVC;
}

@property(nonatomic,weak) UITableView *tableView;

/**点击联系客服后出现的灰色蒙版*/
@property(nonatomic,weak) UIView *hud;
/**点击联系客服后下面出现的选项卡*/
@property(nonatomic,weak) UIView *selectView;

@property(nonatomic,copy)NSString * signdays;

@end

@implementation LXMineViewController

//...........................................我是分割线...........................................//
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpTableView];
    self.signdays = @"0";

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if(LoginState){
        [[LXDataManager manager] getUserInfoWithComplete:^(BOOL success, id res) {
            NSLog(@"%@",res);
            if(success){
                [self headerViewEvent];
                [self.tableView reloadData];
            } else{
                
            }
        }];
        
        [[LXDataManager manager] getSignDaysWithPrama:@{@"user_id":User_id} complete:^(BOOL success, id res) {
            if(success){
                id times = res[@"data"][@"signtimes"];
                if([times isKindOfClass:[NSNumber class]]){
                    self.signdays = [times stringValue];
                }else if([times isKindOfClass:[NSString class]]){
                    self.signdays = times;
                }
                else{
                    self.signdays = @"0";
                }
                [self.tableView reloadData];
            }
        }];
    }else{
            LXLoginViewController * loginVC =  [[LXLoginViewController alloc] init];
            loginVC.closeCallBack = ^(){
                [self.navigationController popToRootViewControllerAnimated:NO];
                [self.navigationController.tabBarController setSelectedIndex:0];
            };
            [self presentViewController:loginVC animated:YES completion:nil];
    }
    self.navigationController.navigationBar.hidden = YES;
    
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
//...........................................我是分割线...........................................//
#pragma mark - 初始化tableView
- (void)setUpTableView
{
    
    LXMineHeaderView *mineHeaderView = [[LXMineHeaderView alloc] init];
    mineHeaderView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, MineRatio(220));
    mineHeaderView.leftHandle = ^(){
        [self.navigationController popViewControllerAnimated:YES];
    };
    mineHeaderView.rightHandle = ^(){
        SettingTableViewController * setting = [[SettingTableViewController alloc] init];
        [self.navigationController pushViewController:setting animated:YES];
    };
    [[LXDataManager manager] getGreenBeansCountWithPrama:nil complete:^(BOOL success, id res) {
       
        if (success) {
            NSNumber *greenBeansCount = res[@"data"][@"beannums"];
            NSString *greenBeansNums = [NSString stringWithFormat:@"%@",greenBeansCount];
            [mineHeaderView.greenBeansButton setTitle:greenBeansNums forState:UIControlStateNormal];
        }
        
    }];
    
    [mineHeaderView.greenBeansButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [mineHeaderView.greenBeansButton setImage:[UIImage imageNamed:@"gr-dou"] forState:UIControlStateNormal];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height+20) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];

    tableView.contentInset        = UIEdgeInsetsMake(-20, 0, 0, 0);
    
    tableView.tableHeaderView = mineHeaderView;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.showsHorizontalScrollIndicator = NO;
    
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    self.tableView = tableView;
    self.mineHeaderView = mineHeaderView;
    
    [self.tableView registerClass:[LXPreparePayViewCell class] forCellReuseIdentifier:LXPreparePayViewCellID];
    [self.tableView registerClass:[LXNoHighLightViewCell class] forCellReuseIdentifier:LXNoHighLightViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXMineCommissionViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:LXMineCommissionViewCellID];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:LXCommonCellID];
}
//...........................................我是分割线...........................................//

#pragma mark - tableView头部视图事件处理
- (void)headerViewEvent
{
    LXUser * user = [LXUser shareUser];
    //返回
    self.mineHeaderView.leftHandle = ^{
        [self.navigationController popViewControllerAnimated:YES];
    };
    
    //设置
    self.mineHeaderView.rightHandle = ^{
        SettingTableViewController *settingVc = [[SettingTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
        [self.navigationController pushViewController:settingVc animated:YES];
    };
    if([LXUser shareUser].headerImage.length!=0){
        [self.mineHeaderView.userImageView sd_setImageWithURL:[NSURL URLWithString:[LXUser shareUser].headerImage] placeholderImage:[UIImage imageWithMargin:8 marginColor:[UIColor colorWithRed:69 / 255.0 green:141 / 255.0 blue:39 / 255.0 alpha:1.0] image:[UIImage imageNamed:@"user_icon_default"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            self.mineHeaderView.userImageView.image = [UIImage imageWithMargin:8 marginColor:[UIColor colorWithRed:69 / 255.0 green:141 / 255.0 blue:39 / 255.0 alpha:1.0] image:image];
        }];
 
    }else{
        [self.mineHeaderView.userImageView setImage:[UIImage imageNamed:@"user_icon_default"]];
    }
    
    
    self.mineHeaderView.nameLabel.text = User_nickname;
    self.mineHeaderView.IDLabel.text = [NSString stringWithFormat:@"ID:%@",user.user_id];
    [self.mineHeaderView.greenBeansButton setTitle:user.bean_nums forState:UIControlStateNormal];
}
//...........................................我是分割线...........................................//

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0: return 1;
        case 1: return 2;
        case 2: return 3;
        case 3: return 2;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LXUser * user = [LXUser shareUser];
    switch (indexPath.section) {
        case 0:{
            LXPreparePayViewCell *preparePayCell = [tableView dequeueReusableCellWithIdentifier:LXPreparePayViewCellID];
            return preparePayCell;
        }
        case 1:{
            switch (indexPath.row) {
                case 0:{
                    LXNoHighLightViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LXNoHighLightViewCellID];
                    cell.imageView.image = [UIImage imageNamed:@"assets"];
                    cell.textLabel.text = @"我的资产";
                    cell.textLabel.font = [UIFont systemFontOfSize:12];
                    [cell setBackgroundImageViewHeight:MineRatio(40)];
                    cell.backgroundImageView.transform = CGAffineTransformIdentity;
                    cell.enableUnaderLine = NO;
                    cell.backgroundImage = [UIImage imageNamed:@"brokerage_bg02"];
                    cell.backgroundImageView.transform = CGAffineTransformRotate(cell.backgroundImageView.transform, M_PI);
                    return cell;
                }
                case 1:{
                    LXMineCommissionViewCell *commissionViewCell = [tableView dequeueReusableCellWithIdentifier:LXMineCommissionViewCellID];
                    commissionViewCell.commissionBtn.numberLabel.text = user.commission;
                    commissionViewCell.commissionBtn.nameLabel.text = @"我的佣金";
                    commissionViewCell.commissionBtn.imageIcon.image = [UIImage imageWithMargin:0 marginColor:[UIColor clearColor] image:[UIImage imageNamed:@"commission"]];
                    
                    commissionViewCell.couponBtn.numberLabel.text = @"1";
                    commissionViewCell.couponBtn.nameLabel.text = @"优惠券";
                    commissionViewCell.couponBtn.imageIcon.image = [UIImage imageWithMargin:0 marginColor:[UIColor clearColor] image:[UIImage imageNamed:@"coupons"]];
                    
                    
                    commissionViewCell.signUpBtn.nameLabel.text = @"签到";
                    commissionViewCell.signUpBtn.numberLabel.text = self.signdays;
                    commissionViewCell.signUpBtn.imageIcon.image = [UIImage imageWithMargin:0 marginColor:[UIColor clearColor] image:[UIImage imageNamed:@"Sign-in"]];
                    
                    return commissionViewCell;
                }
            }
        }
        case 2:{
            switch (indexPath.row) {
                case 0:{
                    LXNoHighLightViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LXNoHighLightViewCellID];
                    cell.imageView.image = [UIImage imageNamed:@"assets"];
                    cell.textLabel.text = @"我的特卖";
                    [cell setBackgroundImageViewHeight:MineRatio(50)];
                    cell.backgroundImageView.transform = CGAffineTransformIdentity;
                    cell.enableUnaderLine = YES;
                    cell.backgroundImage = [UIImage imageNamed:@"brokerage_bg02"];
                    cell.backgroundImageView.transform = CGAffineTransformRotate(cell.backgroundImageView.transform, M_PI);
                    return cell;
                }
                case 1:{
                    LXNoHighLightViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LXNoHighLightViewCellID];
                    cell.imageView.image = [UIImage imageNamed:@"setting"];
                    cell.textLabel.text = @"账户设置";
                    [cell setBackgroundImageViewHeight:MineRatio(50)];
                    cell.backgroundImageView.transform = CGAffineTransformIdentity;
                    cell.enableUnaderLine = YES;
                    cell.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor] size:CGSizeMake(ScreenWidth-2*globalMargin, MineRatio(50))];
                    return cell;
                }
                case 2:{
                    LXNoHighLightViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LXNoHighLightViewCellID];
                    cell.imageView.image = [UIImage imageNamed:@"login"];
                    cell.textLabel.text = @"登录方式";
                    [cell setBackgroundImageViewHeight:MineRatio(50)];
                    cell.backgroundImageView.transform = CGAffineTransformIdentity;
                    cell.enableUnaderLine = NO;
                    cell.backgroundImage = [UIImage imageNamed:@"brokerage_bg02"];
                    return cell;
                }
            }
        }
        case 3:{
            switch (indexPath.row) {
                case 0:{
                    LXNoHighLightViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LXNoHighLightViewCellID];
                    cell.imageView.image = [UIImage imageNamed:@"feedback"];
                    cell.textLabel.text = @"意见反馈";
                    [cell setBackgroundImageViewHeight:MineRatio(50)];
                    cell.backgroundImageView.transform = CGAffineTransformIdentity;
                    cell.enableUnaderLine = YES;
                    cell.backgroundImage = [UIImage imageNamed:@"brokerage_bg02"];
                    cell.backgroundImageView.transform = CGAffineTransformRotate(cell.backgroundImageView.transform, M_PI);
                    return cell;
                }
                case 1:{
                    LXNoHighLightViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LXNoHighLightViewCellID];
                    cell.imageView.image = [UIImage imageNamed:@"Customer_service"];
                    cell.textLabel.text = @"联系客服";
                    [cell setBackgroundImageViewHeight:MineRatio(50)];
                    cell.backgroundImageView.transform = CGAffineTransformIdentity;
                    cell.enableUnaderLine = NO;
                    cell.backgroundImage = [UIImage imageNamed:@"brokerage_bg02"];
                    return cell;
                }
            }
        }
    }
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.textLabel.text = [NSString stringWithFormat:@"第%zd组----第%zd行",indexPath.section,indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) return MineRatio(88);
    if (indexPath.section == 1 && indexPath.row == 0) return MineRatio(40);
    if (indexPath.section == 1 && indexPath.row == 1) return 70;
    return MineRatio(50);
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return globalMargin;
}

//...........................................我是分割线...........................................//
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //TODO:跳转登录方式页面
    if (indexPath.section == 2 && indexPath.row == 2) {
//        LXLoginViewController *loginVc = [[LXLoginViewController alloc] init];
//        [self presentViewController:loginVc animated:YES completion:nil];
        LXLoginStyleViewController *loginStyleVc = [[LXLoginStyleViewController alloc] init];
        
        [self.navigationController pushViewController:loginStyleVc animated:YES];

    //TODO:跳转用户反馈页面
    }else if (indexPath.section == 3){
        if (indexPath.row == 0) {
            LXFeedbackViewController *feedbackVc = [[LXFeedbackViewController alloc] init];
            [self.navigationController pushViewController:feedbackVc animated:YES];
        //TODO:弹出打电话view
        }else{
            UIView *hud = [[UIView alloc] init];
            hud.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
            hud.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
            self.hud = hud;
            [[[UIApplication sharedApplication].delegate window] addSubview:hud];
            
            UIView *selectView = [[UIView alloc] init];
            selectView.backgroundColor = [UIColor whiteColor];
            selectView.frame = CGRectMake(0, ScreenHeight *0.8, ScreenWidth, ScreenHeight *0.2);
            self.selectView = selectView;
            [hud addSubview:selectView];
            
            UIView *topCutLine = [[UIView alloc] init];
            topCutLine.x = 0;
            topCutLine.y = selectView.height * 0.33;
            topCutLine.width = ScreenWidth;
            topCutLine.height = 1;
            topCutLine.backgroundColor = [UIColor lightGrayColor];
            [selectView addSubview:topCutLine];
            
            UIView *bottomCutLine = [[UIView alloc] init];
            bottomCutLine.x = 0;
            bottomCutLine.y = selectView.height * 0.66;
            bottomCutLine.width = ScreenWidth;
            bottomCutLine.height = 1;
            bottomCutLine.backgroundColor = [UIColor lightGrayColor];
            [selectView addSubview:bottomCutLine];
            
            UILabel *contactLabel = [[UILabel alloc] init];
            contactLabel.text = @"拨打客服电话";
            contactLabel.textAlignment = NSTextAlignmentCenter;
            contactLabel.font = [UIFont systemFontOfSize:14];
            contactLabel.x = 0;
            contactLabel.y = 0;
            contactLabel.width = ScreenWidth;
            contactLabel.height = topCutLine.y;
            [selectView addSubview:contactLabel];
           
            UIButton *phoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [phoneBtn addTarget:self action:@selector(phoneBtnClick) forControlEvents:UIControlEventTouchUpInside];
            [phoneBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [phoneBtn setTitle:@"027-85666666" forState:UIControlStateNormal];
            phoneBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            phoneBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
            phoneBtn.x = 0;
            phoneBtn.y = topCutLine.botton;
            phoneBtn.width = ScreenWidth;
            phoneBtn.height = contactLabel.height;
            [selectView addSubview:phoneBtn];
            
            UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
            [cancleBtn setTitleColor:LXMainColor forState:UIControlStateNormal];
            [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
            cancleBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            cancleBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
            cancleBtn.x = 0;
            cancleBtn.y = bottomCutLine.botton;
            cancleBtn.width = ScreenWidth;
            cancleBtn.height = contactLabel.height;
            [selectView addSubview:cancleBtn];
        }
    //TODO:跳转我的特卖页面
    }else if (indexPath.section == 2 && indexPath.row == 0){
        LXMySaleViewController *mySaleVc = [[LXMySaleViewController alloc] init];
        [self.navigationController pushViewController:mySaleVc animated:YES];
    //TODO:跳转账户设置页面
    }else if (indexPath.section == 2 && indexPath.row == 1){
        LXAccountSettingViewController *accountSettingVc = [[LXAccountSettingViewController alloc] init];
        [self.navigationController pushViewController:accountSettingVc animated:YES];

    }
}

#pragma mark - alert事件处理
- (void)phoneBtnClick
{
    NSString *phone = [NSString stringWithFormat:@"telprompt://027-85666666"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];
}

- (void)cancleBtnClick
{
    [self.hud removeFromSuperview];
    [self.selectView removeFromSuperview];
}

//...........................................我是分割线...........................................//

#pragma mark - cell下划线顶到左边
//............................................................................................//
//....................................下面两个方法必须同时实现....................................//
//............................................................................................//

- (void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
//............................................................................................//
//....................................以上两个方法必须同时实现....................................//
//............................................................................................//
@end
